package com.bdqn.controller;
import com.alibaba.fastjson.JSON;
import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysRoleService;
import com.bdqn.service.SysUserService;
import com.bdqn.utils.Constants;
import com.bdqn.utils.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger log = Logger.getLogger(SysUserController.class);

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    @PostMapping("/login")
    public String doLogin(RuntimeException e,HttpServletRequest request, HttpSession session, @RequestParam String account, @RequestParam String password){
        log.debug("登录方法");
        SysUser sysUser = sysUserService.getAccount(account,password);
        if (null != sysUser){
            session.setAttribute(Constants.USER_SESSION,sysUser);
            session.setAttribute("USER_SESSION",sysUser);
            return "redirect:/user/toMain";
        }else {
            session.setAttribute("error","账号或密码错误");
            return "login";
        }

    }

    @GetMapping("/list")
    public String getUserList(Model model, String queryRealName, Integer queryRoleId, @RequestParam(defaultValue = "1")Integer pageIndex){
        List<SysUser> userList = null;
        List<SysRole> sysRoles = null;
        try{
            //设置页面容量
            int pageSize = Constants.pageSize;
            //总数量
            int totalCount = sysUserService.getCount();
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex); // 设置当前页数
            pages.setPageSize(pageSize);       // 设置一页显示数据量
            pages.setTotalCount(totalCount);   // 设置总数据量
            int totalPageCount = pages.getTotalPageCount();
            if (pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList = sysUserService.getUserList((pageIndex-1)*pageSize,pageSize,queryRealName,queryRoleId);
            sysRoles = sysRoleService.getAll();
            model.addAttribute("userList",userList);  // 用户信息
            model.addAttribute("totalCount",pages.getTotalCount()); // 分页信息
            model.addAttribute("currentPageNo",pages.getPageNo());
            model.addAttribute("totalPageCount",pages.getTotalPageCount());
            model.addAttribute("queryRealName",queryRealName); // 查询条件回显
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("roleList",sysRoles);
        }catch (Exception e){
            e.printStackTrace();
            log.error("用户列表接口访问失败");
            return "redirect:/user/toSysError";
        }
        return "/sysUser/list";
    }

    @ResponseBody // 让返回的内容原样输出到页面（通常用于ajax处理）
    @PostMapping(value = "/checkOldPwd",produces = {"application/json;charset=UTF-8"})
    public String getPwd(String oldPassword, HttpServletResponse response,HttpSession session) throws IOException {
        // 获取登录账号的用户信息
        SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        // 查询输入密码是否和数据库用户密码相同
        String account = sysUser.getAccount();
        int pwd = sysUserService.getPwd(oldPassword,account);
        Map<String,String> map = new HashMap<>();
        String result = "true";
        // 判断是否与旧密码相同 true:成功 false:失败
        if (pwd == 1){
            result = "true";
        }else {
            result = "false";
        }
        map.put("result",result);
        return JSON.toJSONString(map);
    }
    @ResponseBody // 让返回的内容原样输出到页面（通常用于ajax处理）
    @PostMapping(value = "/savePassword",produces = "text/html; charset=UTF-8")
    public String savePassword(String newPassword,HttpSession session,HttpServletResponse response) throws IOException {
        // 获取登录账号的用户信息
        SysUser sysUser = (SysUser)session.getAttribute(Constants.USER_SESSION);
        // 调用方法修改密码
        int iRet = sysUserService.savePassword(sysUser.getAccount(),newPassword);
        String result = null;
        if (iRet == 1){
            result = "<script>alert('修改密码成功！');window.location='http://localhost:8080/724_war_exploded/user/toUpdatePwd'</script>";
        }else{
            result = "<script>alert('修改密码失败！');window.location='http://localhost:8080/724_war_exploded/user/toUpdatePwd'</script>";
        }
        return result;
    }
    @ResponseBody  // 让返回的内容原样输出到页面（通常用于ajax处理）
    @GetMapping(value = "/userExist")
    public String getAccountC(String account){
        // 查询是否有相同的账号
        int accountC = sysUserService.getAccountC(account);
        Map<String,Integer> map = new HashMap<>();
        if (accountC > 1){
            map.put("exist", 1);
        }else if (accountC == 0){
            map.put("exist", 0);
        }
        return JSON.toJSONString(map);
    }
    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION) == null){
            return "redirect:/user/toLogin";
        }
        return "frame";
    }
    // 退出
    @RequestMapping("/logout")
    public String tui(HttpSession session){
        session.removeAttribute("USER_SESSION");
        session.invalidate();
        return "login";
    }

    @PostMapping("/add")
    public String doAdd(Model model, HttpServletRequest request, HttpSession session, SysUser sysUser, MultipartFile idPic, MultipartFile workPic) {
        SysUser loginUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        sysUser.setCreatedUserId(loginUser.getId());
        sysUser.setCreatedTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

        // 文件上传到服务器的真实位置 C:\Service\apache-tomcat-9.0.91\webapps\724\web\statics\...
        String uploadPath = session.getServletContext().getRealPath(Constants.UPLOAD_PATH);

        Map<String, String> msg = new HashMap<>();
        // 身份证照片上传
        if (idPic != null) {
            // 提取文件上传的方法
            String idPicPath = multipartFileUpload(uploadPath, idPic, msg);
            // Web访问的路径（不是文件上传的磁盘位置）
            if (idPicPath == null) {
                String uploadFileError = msg.get("uploadFileError");
                request.setAttribute("idPicUploadError", uploadFileError);
                return "sysUser/add";
            }
            // 设置身份证照片路径
            sysUser.setIdPicPath(idPicPath);
        }
        // 工作证照片上传
        if (workPic != null) {
            // 提取文件上传的方法
            String workPicPath = multipartFileUpload(uploadPath, workPic, msg);
            // Web访问的路径（不是文件上传的磁盘位置）
            if (workPicPath == null) {
                String uploadFileError = msg.get("uploadFileError");
                request.setAttribute("workPicUploadError", uploadFileError);
                return "sysUser/add";
            }
            // 设置工作证照片路径
            sysUser.setWorkPicPath(workPicPath);
        }

        // 调用业务逻辑层完成用户添加
        int add = sysUserService.add(sysUser);
        if (add==1) { // 成功重定向到列表页
            return "redirect:/user/list";
        }
        return "sysUser/add";
    }

    /**
     * 多部件文件上传（错误信息临时保存在request作用域uploadFileError属性中）
     *
     * @return 成功返回文件上传地址，返回null表示文件上传失败
     */
    public synchronized String multipartFileUpload(String uploadPath, MultipartFile multipartFile, Map<String, String> msg) {
        String uploadFilePath = null; // 文件上传地址，返回null表示文件上传失败

        // 定义文件存放目录
        log.debug("上传文件路径：" + uploadPath);

        if (!multipartFile.isEmpty()) {
            // 获取上传的文件信息
            String originalFile = multipartFile.getOriginalFilename(); // 原文件名称
            log.debug("原文件名称为：" + originalFile);
            String prefix = FilenameUtils.getExtension(originalFile); // 原文件后缀
            log.debug("原文件后缀为：" + prefix);
            long fileSize = multipartFile.getSize(); // 原文件大小
            log.debug("上传文件大小：" + fileSize);

            // 判断上传的文件是否符合要求
            if (fileSize > Constants.MAX_FILE_SIZE) { // 上传文件大小不能超过500KB
                msg.put("uploadFileError", " * 上传文件大小不得超过 5MB");
                return uploadFilePath;
            }
            if (prefix != null && !(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("pneg"))) {
                msg.put("uploadFileError", " * 上传文件格式只能是jpg、jpeg、png、pneg");
                return uploadFilePath;
            }

            // 确定文件存储名称
            String fileName = System.nanoTime() + RandomUtils.nextInt(1000) + "_Personal." + prefix;
            log.debug("新生成的文件名为：" + fileName);

            // 将上传的文件保存到目标位置
            File targetFile = new File(uploadPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs(); // 如果目录不存在则生成目录
            }
            // 保存文件
            try {
                // 存储物理地址 + 生成的文件名称
                multipartFile.transferTo(new File(targetFile, fileName));
            } catch (IOException e) {
                e.printStackTrace();
                msg.put("uploadFileError", " * 文件上传失败！");
                return uploadFilePath;
            }
            // 文件上传完成就可以拿到地址
            // /statics/upload/98020913201542_Personal.jpg
            uploadFilePath = "/" + Constants.UPLOAD_PATH + "/" + fileName;
        }

        // 返回文件上传成功后的地址，失败时返回null，并且将失败信息记录到
        return uploadFilePath;
    }



    @GetMapping("/add")
    public String toAdd(){
        return "/sysUser/add";
    }
    @GetMapping("/toUpdatePwd")
    public String toUpdatePwd(){
        return "/sysUser/updatePassword";
    }

    @RequestMapping(value = "/toLogin")
    public String login(){
        log.debug("跳转到登录页面");
        return "login";
    }

    // 跳转到登录页面
    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }
}
